<?php

namespace App\Admin\Controllers;

use App\Models\Card;
use App\Admin\Extensions\Tools\ReleasePost;
use App\Admin\Extensions\Tools\UserGender;
use App\Admin\Extensions\Tools\BuildGender;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid\Tools\AbstractTool;
use Illuminate\Support\Facades\Request;


class CardController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Card::class, function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->like('number', '卡号');
                $filter->like('amount', '面额');
                $filter->like('mobile', '充值用户');
                $filter->where(function ($query) {
                    switch ($this->input) {
                        case 'yes':
                            $query->where('user_id','<>','');
                            break;
                        case 'no':
                            $query->where('user_id','=',null);
                            break;
                    }
                }, '使用情况')->radio([
                    '' => '全部',
                    'yes' => '已使用',
                    'no' => '未使用',
                ]);

                $filter->between('updated_at', '时间筛选')->date();
            });
            $grid->define_preg(url('admin/card/create'), '生成充值卡');
            $grid->id('ID')->sortable();
            $grid->column('number', '卡号');
            $grid->column('password', '密码');
            $grid->column('amount', '面额');
            $grid->column('user.mobile', '充值用户');
            $grid->column('over_time', '失效时间');
            $grid->created_at('创建时间');
            $grid->updated_at('更新(充值)时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Card::class, function (Form $form) {
            $form->saving(function (Form $form) {
                //面额
                if ($form->amount < 0 || !is_numeric($form->amount)) {
                    throw new \Exception('面额格式错误！');
                }
                //卡号前缀
                $prefix = $form->prefix;
                if($form->card_length-strlen($prefix)< 4){
                    throw new \Exception('卡号长度和前缀长度差不能少于4位！');
                }
                //卡号长度
                if($form->card_length<8) {
                    throw new \Exception('卡号不能少于8位！');
                }
                //密码长度
                if($form->password_length<6) {
                    throw new \Exception('密码不能少于6位！');
                }
                //有效期
                if($form->overtime<date('Y-m-d H:i:s', time())) {
                    throw new \Exception('过期时间必须在当前时间之后！');
                }
                //卡号长度-前缀
                $rand_length = $form->card_length-strlen($prefix);
                $t = 0;
                //卡号组成
                switch ($form->form){
                    //纯数字
                    case '0';
                        $str='0123456789';
                        break;
                    //数字加字母
                    case '1';
                        $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                        break;
                    //小写字母
                    case '2';
                        $str='abcdefghijklmnopqrstuvwxyz';
                        break;
                    //大写字母
                    case '3';
                        $str='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    default;
                        $str='0123456789';
                        break;

                }
                $len = strlen($str)-1;
                $password_str = '0123456789';
                for($i = 0; $i < $form->num; $i++) {
                    $number = $prefix;
                    //卡号
                    for($x=0;$x<$rand_length;$x++){
                        $num = mt_rand(0,$len);
                        $number .= $str[$num];
                    }
                    //密码
                    $password = '';
                    for($z=0;$z<$form->password;$z++){
                        $num = mt_rand(0,9);
                        $password .= $password_str[$num];
                    }
                    if(Card::where('number',$number)->first()) {
                        $i--;
                    } else {
                        $t++;
                        $password = mt_rand(100000, '999999');
                        $array = [
                            'number'=>$number,
                            'password'=>$password,
                            'amount'=>$form->amount,
                            'editor'=>'admin',
                            'over_time'=>$form->overtime
                        ];
                        Card::create($array);
                    }
                }
                echo '<script>alert("生成充值卡成功！");history.go(-2);</script>';die;
            });
            $form->currency('amount', '面额');
            $number = rand(1000,9999);
            $form->text('prefix', '卡号前缀')->default($number);
            $form->radio('form', '卡号组成')->options(['0' => '纯数字', '1'=> '数字加字母', '2'=> '小写字母', '3'=> '大写字母'])->default('0');
            $form->text('card_length', '卡号长度')->default(8);
            $form->text('password_length', '密码长度')->default(6);
            $form->datetime('overtime', '失效时间');
            $form->text('num', '生成数量')->rules('required');
        });
    }
}
